package cn.aixuxi.notebank.controller;

import cn.aixuxi.notebank.authc.JwtToken;
import cn.aixuxi.notebank.constant.DefConstant;
import cn.aixuxi.notebank.dto.UserInputDTO;
import cn.aixuxi.notebank.entity.UserEntity;
import cn.aixuxi.notebank.service.UserService;
import cn.aixuxi.notebank.util.JwtUtils;
import cn.aixuxi.notebank.util.RedisUtils;
import cn.hutool.core.lang.UUID;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 类描述
 *
 * @author ruozhuliufeng
 * @version 1.0
 * @date 2020/10/24 20:07
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    UserService userService;

    /**
     * 功能描述: 根据激活码激活用户
     *
     * @param activeCode 激活码
     * @return : 返回主页
     * @author : ruozhuliufeng
     * @date : 2020/12/29 13:47
     */
    @GetMapping("/active")
    public String active(String activeCode, HttpSession session) {
        String errMsg;
        // 获取用户
        UserEntity userEntity = userService.findByActiveCode(activeCode);
        if (userEntity == null) {
            // 未找到该用户
            errMsg = "用户未发现，请检查激活码是否正确！";
            session.setAttribute("errMsg", errMsg);
            return "user/error";
        }
        String code = redisUtils.get(userEntity.getEmail()).toString();
        if (code == null) {
            errMsg = "激活码已失效，请点击链接重新发送激活码！";
            activeCode = UUID.randomUUID().toString();
            // TODO 重新发送激活邮件
            redisUtils.set(userEntity.getEmail(), activeCode, DefConstant.ACTIVECODE_EXPIRE_TIME);
            session.setAttribute("errMsg", errMsg);
            return "user/error";
        } else if (code.equals(activeCode)) {
            // 激活码与缓存中一致
            userEntity.setStatus(DefConstant.ACTIVE);
            userEntity.setActiveCode("");
            userService.updateById(userEntity);
            redisUtils.del(userEntity.getEmail());
            return "user/center";
        } else {
            // 激活码与缓存不一致
            errMsg = "激活码不一致，请重新确认！";
            session.setAttribute("errMsg", errMsg);
            return "user/error";
        }

    }
}
